import {createAsyncThunk} from "@reduxjs/toolkit";
import {DsBase, DsDescription, DsFile, DsServe} from "@/schemas/datasource.ts";
import {ListQuery} from "@/schemas/invoke.ts";
import {invokeAllQuery, invokeDuckQuery, invokeListQuery, invokeOperationOne} from "@/communicate/rust-invoke.ts";
import {queryTen} from "@/common/default-some.ts";


const fetchDatasource = async (query: ListQuery, rejectWithValue: any) => {
    const resp = await invokeListQuery<DsBase>(
        'ds/list', 'ListQuery', query
    )
    if (resp.ok) return resp.data?.result || []
    return rejectWithValue('获取项目列表失败！')
}

const fetchDsDescription = async (dsId: string, rejectWithValue: any) => {
    const resp = await invokeAllQuery<DsDescription>(
        'ds/description/all',
        'OperateDatasource',
        {id: dsId},
    )
    if (resp.ok) return resp.data
    return rejectWithValue("获取数据源描述失败！")
}

export const ListDatasource = createAsyncThunk(
    "datasource/list",
    async (query: ListQuery, {rejectWithValue}) => await fetchDatasource(query, rejectWithValue),
)


export const AllDsDescription = createAsyncThunk(
    "ds/description/all",
    async (dsId: string, {rejectWithValue}) => await fetchDsDescription(dsId, rejectWithValue)
)

export const CreateDsFile = createAsyncThunk(
    "ds/file/create",
    async (data: DsFile, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ds/file/create',
            'CreateDsFile',
            data
        )
        if (resp.ok) return await fetchDatasource(queryTen, rejectWithValue)
        return rejectWithValue('添加数据源失败')
    }
)

export const CreateDsServe = createAsyncThunk(
    "ds/serve/create",
    async (data: DsServe, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ds/serve/create',
            'CreateDsServe',
            data
        )
        if (resp.ok) return await fetchDatasource(queryTen, rejectWithValue)
        return rejectWithValue('添加数据源失败')
    }
)


export const LoadDatasource = createAsyncThunk(
    "ds/load",
    async (data: DsBase, {rejectWithValue}) => {
        const resp = await invokeDuckQuery<any>(
            "ds/load",
            'OperateDatasource',
            {id: data.id as string}
        )
        if (resp.ok) return {selected: data, sourceData: resp.data?.result || []}
        return rejectWithValue('加载数据失败！')
    }
)

export const SelectedDatasource = createAsyncThunk(
    "ds/selected",
    async (data: DsBase, {rejectWithValue}) => {
        const resp = await invokeDuckQuery<any>(
            "ds/table/all",
            'OperateDatasource',
            {id: data.id as string}
        )
        if (resp.ok) return {selected: data, sourceData: resp.data?.result || []}
        return rejectWithValue('数据拉取失败！请尝试【刷新/加载】数据')
    }
)